
'use strict';
const app = require('tcb-admin-node');
const tcb_config = {env: 'meatom04-01-2gue0fnr49a26808'};
app.init(tcb_config).auth();
const db = app.database();

let event_param
function checkVerCon(param){
  event_param = param
  return db.collection("VersionCon").where({ 
    version: event_param.version,
    platform : event_param.platform,
    key: event_param.key,
  }).get().then(res => {
    if(res.data && res.data.length){
      return updateVersion(res.data[0]._id)
    }else{
      return addVersion()
    }
  }).catch(error => {
    return error
  })
}
function addVersion(){
  return db.collection("VersionCon").add(event_param).then(res => {
    event_param['_id'] = res.id
    return event_param
  }).catch(error =>{
    return error
  })
}
function updateVersion(id){
    return db.collection("VersionCon").doc(id).set({
      key: event_param.key,
      value: event_param.value,
      platform : event_param.platform,
      version: event_param.version,
      type: event_param.type
    }).then(res => {
      event_param['_id'] = id
      event_param.update = true
      return event_param
    }).catch(error => {
      return error
    })
}
exports.main = async (event, context, callback) => {
    return await checkVerCon(event)
};
